from django.shortcuts import render
from rest_framework import status
from rest_framework.views import APIView
from meiduo_mall.utils.qq_sdk import OAuthQQ
from rest_framework.response import Response
from rest_framework_jwt.settings import api_settings
from meiduo_mall.utils.jwt_token import get_jwt_token
from . import serializers

from oauth.models import OauthQQUser


class OauthQQurlView(APIView):
    """
    返回qq验证路径，浏览器打开
    """

    def get(self, request):
        """
        拼接qq授权路径
        :param next:
        :return: qq授权路径
        """
        # 获取参数
        next = request.query_params.get('next')
        oauthqq = OAuthQQ(state=next)

        login_url = oauthqq.get_qq_login_url()

        return Response({'login_url': login_url})


class OauthQQopenidView(APIView):
    def get(self, request):
        # 获取参数code判断是否存在
        code = request.query_params.get('code')
        # 根据code获取token
        if not code:
            return Response({'message': '缺省code'}, status=status.HTTP_400_BAD_REQUEST)
        # 根据toekn获取openid
        oauthqq = OAuthQQ()
        try:
            access_token = oauthqq.get_access_token(code)
            openid = oauthqq.get_openid(access_token)
        except:
            return Response({'message': 'QQ服务器异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        # 判断用户是否绑定,
        try:
            qq_user = OauthQQUser.objects.get(openid=openid)
        except OauthQQUser.DoesNotExist:
            # 如果没绑定则，生成自己的access_token,里面包含openid
            token = oauthqq.generate_openid_token(openid)
            return Response({'access_token': token})

        else:  # 表示成功后
            # 如果绑定了，则使用JWT生成token,里面包含用户openid,用户名，用户(不是QQ里的)id，前端会根据返回的数据里是否有suer_id判断返回给客户端什么页面
            user = qq_user.user
            # jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            # jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            # pay_load = jwt_payload_handler(user)
            # token = jwt_encode_handler(pay_load)
            # 生成JWT token用于状态保持
            token = get_jwt_token(user)

            response = Response({
                'token': token,
                'username': user.username,
                'user_id': user.id
            })

        return response

    # 也可以继承genericCreateAPIView,指定serializer,下面就不用写了
    def post(self, request):

        serializer = serializers.OauthQQserializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()

        response = Response({
            'token': user.token,
            'user_id': user.id,
            'username': user.username
        })

        return response
